import { Button, DataGrid, LoadIndicator, Popup, SelectBox, TextBox } from "devextreme-react";
import "./index.less"
import { useModel } from "umi";
import { intl } from "@/utils";
import DevTreeRight from "./DevTree/index";
import SetReclassiFiedItem from "./SetReclassiFiedItem";
import { getSubjectList, getSubjectType } from "@/pages/ReportFinancial/service";
import { AdjustingEntryKMMapSave, getKMMapDataList, updateMap, } from "./service";
import { DevToolBar, CpasIcon, DevGrid, LayoutB, SortableDevGrid, DevPopup } from '~/public/cpas-ui';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import AntTabs, { HocVerticalLeftStyleTab, HocVerticalRightStyleTab } from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import { adjustingEntryInit, KMMapanalysisMap } from "../ClassiFication/service";
import notify from "devextreme/ui/notify";



const SetClassiFication: React.FC<any> = React.forwardRef((props: any, ref) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;
    const { width, height, isQC } = props

    const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", marginRight: '10px' };
    const [openVisible111111, setOpenVisible111111] = useState<boolean>(false);

    const diaParams = useRef<any>();
    const tableRowData = useRef<any>();
    const devGridRef = useRef<any>();
    const DeletePopupRef = useRef<any>();
    const SetReclassiFiedItemRef = useRef<any>();

    // const [state,setState] = useState<boolean>(false);
    const [visible, setVisible] = useState<boolean>(false);
    const [size, setSize] = useState<any>({ width, height });
    const [dataSortable, SetDataSortable] = useState<any[]>([])
    const [ficationTabsData, setFicationTabsData] = useState<any>([])
    const [AccountList, setAccountList] = useState<any[]>([])
    const [AccountFilterData, setAccountFilterData] = useState<any[]>([])
    // const [draggedTreeNode, setDraggedTreeNode] = useState<any>({});
    const draggedTreeNode = useRef<any>({});
    const [tbsStates, setTbsStates] = useState<any>('0');
    const getKMMapDataLists = async (params: any) => {
        devGridRef.current.instance.beginCustomLoading();
        const { BillID, DataId } = params
        const r = await getKMMapDataList({
            dbname,
            billID: BillID,
            Data_ID: DataId
        })
        if (r) devGridRef.current.instance.endCustomLoading();
        SetDataSortable(r)
    }

    // 获取切换数据
    const getSubjectTypeData = async (params: { DataId: any; }) => {
        const { DataId } = params
        const res = await getSubjectType({
            dbname,
            Data_ID: DataId,
        });
        if (res.success) {
            res.data.unshift({ code: "0", type: "全部" })
            setFicationTabsData(res.data)
            setTbsStates('0');
        }
        return []
    };

    // 获取树表格数据
    const getSubjectListDatas = async (params: { DataId: any; }) => {
        const { DataId } = params
        const res = await getSubjectList({
            dbname,
            Data_ID: DataId,
            isHasFZZ: true,
        });
        if (res.success) {
            setAccountFilterData(res.data)
            setAccountList(res.data);
        }

    };

    // 每次点击触发接口事件 进行右侧树渲染和列表的过滤数据展示
    useImperativeHandle(ref, () => ({
        show: async (params: any) => {
            setOpenVisible111111(true);
            diaParams.current = params;
            setVisible(true);
            // setDraggedTreeNode({});
            draggedTreeNode.current = {};
            await getKMMapDataLists(params);
            await getSubjectTypeData(params);
            await getSubjectListDatas(params);
            setTbsStates('0');
            setOpenVisible111111(false);

        },
    }))

    // 点击关闭按钮逻辑
    const onHiding = () => {


        diaParams.current.cancelClick();
        setVisible(false);
        tableRowData.current = {};
    }

    const columns = [
        {
            dataField: "YSKMBH",
            dataType: "string",
            caption: "科目编号",
            width: 100,
            alignment: "left",
            allowEditing: false,
            allowUpdating: false,
        },
        {
            dataField: "KMMC",
            dataType: "string",
            caption: "科目名称",
            width: 200,
            alignment: "left",
            allowEditing: false,
            allowUpdating: false,
        },
        {
            dataField: "CFLNo",
            dataType: "string",
            caption: "对方科目编号",
            width: 120,
            alignment: "left",
            allowEditing: false,
            allowUpdating: false,
        },
        {
            dataField: "CFLName",
            dataType: "string",
            caption: "对方科目名称",
            width: 160,
            alignment: "left",
            allowEditing: false,
            allowUpdating: false,
            cellRender: (cell: any) => {
                return <div style={{ display: "flex", justifyContent: "space-between" }}>
                    <span style={{ marginLeft: "5px" }}>{cell.data.CFLName}</span>
                    <span style={{ marginRight: "10px" }}>
                        {/* 点击 清空 */}
                        <CpasIcon type='icon-chexiao' onClick={async () => {
                            DeletePopupRef.current.show({
                                title: "提示",
                                okCallback: async () => {
                                    devGridRef.current.instance.cellValue(tableRowData.current.rowIndex, 'CFLName', "");
                                    devGridRef.current.instance.cellValue(tableRowData.current.rowIndex, 'CFLNo', "");
                                }
                            });
                        }} />
                    </span>
                </div>
            }
        },
        // {
        //     // dataField: "",
        //     // dataType: "string",
        //     caption: "操作列",
        //     width: 130,
        //     alignment: "center",
        //     cellRender: () => {
        //         return <span onClick={() => {
        //             devGridRef.current.instance.cellValue(tableRowData.current, 'CFLName', "");
        //             devGridRef.current.instance.cellValue(tableRowData.current, 'CFLNo', "");
        //         }}>
        //             点击
        //         </span>
        //     }
        // },
    ]
    // 右侧 切换方法
    const getSubjectListData = async (r: string) => {
        if (AccountList) {
            if (r === "全部") {
                setAccountFilterData(AccountList)
            } else {
                const KMLXData = AccountList.filter((item: any) => {
                    return item.KMLX && item.KMLX.includes(r)
                })
                setAccountFilterData(KMLXData)
            }
        }
    };

    const AccountTabsClick = useCallback(async (r: any,) => {
        setTbsStates(r);
        ficationTabsData.map((item: any) => {
            if (r === item.code) {
                getSubjectListData(item.type);
            }
        })
    }, [ficationTabsData, AccountList])
    const onItemClick = async (e: any, tableIndex: number) => {
        if (!e.itemNames3) {
            return notify("此科目未对应报表项目，请先对科目进行对应后，再进行调整", "error", 2000);
        }
        if (tableIndex >= 0) {
            //  66 核算项目类型  99 辅助账
            let tempCFLName = e.level === 66 ? e.YSKMMC : e.name;
            let tempCFLNo = e.level === 66 ? e.YSKMBH : e.code;
            //  66 核算项目类型  99 辅助账
            devGridRef.current.instance.cellValue(tableIndex, 'CFLName', tempCFLName);
            devGridRef.current.instance.cellValue(tableIndex, 'CFLNo', tempCFLNo);
            await updateMap({
                dbname, //1
                billID: diaParams.current.BillID, //1
                YSKMBH: `${e.YSKMBH}`, //1
                GUID: tableRowData.current.GUID, //1
                HSXMLXMC: e.HSXMLXMC,//1
                HSXMLXBH: e.HSXMLXBH,//.
                KMMC: e.KMMC,//.
                KMBH: e.KMBH,//.
                HSXMMC: e.level === 66 ? "" : e.HSXMMC,//.
                HSXMBH: e.level === 66 ? "" : e.HSXMBH,//.
                YSHSXMMC: e.level === 99 ? e.YSHSXMMC : "",
                YSHSXMBH: e.level === 99 ? e.YSHSXMBH : "", //
                itemNames3: e.itemNames3,//.
                YSKMMC: e.YSKMMC,//.
                PKMBH: e.PKMBH//.
            });
            return;
        }
        return notify("请对应表格的位置", 'error', 2000);
    }
    function leftContainer() {
        return (
            <div style={{ width: '98%', height: '100%', }}>
                {
                    useMemo(() => {
                        return <SortableDevGrid
                            className="grid_Style devHeadersCenter"
                            ref={devGridRef}
                            id="GUID"
                            dataSource={dataSortable}
                            width='100%'
                            height='100%'
                            keyExpr="GUID"
                            defaultColumns={columns}
                            showBorders={true}
                            showRowLines={true}
                            showColumnLines={true}
                            allowColumnResizing={true}
                            columnResizingMode="widget"
                            headerFilter={{ visible: false }}
                            filterPanel={{ visible: false }}
                            filterRow={{ visible: false }}
                            paging={{
                                enabled: false
                            }}
                            editing={{
                                allowAdding: false,
                                allowUpdating: true,
                                allowDeleting: false,
                                mode: "cell"
                            }}
                            selection={{
                                allowSelectAll: false,
                            }}
                            gridDragEnd={(toDataIndex: any, toData: any) => {
                                tableRowData.current = { ...toData, rowIndex: toDataIndex };
                                onItemClick(draggedTreeNode.current, toDataIndex);
                            }}
                            // onSaved={SavedData}
                            onCellClick={(res: any) => {
                                console.log(res, 'res.rowIndex----');
                                const { rowType, data, rowIndex } = res;
                                if (rowType === 'data') {
                                    tableRowData.current = { ...data, rowIndex: rowIndex }
                                }
                            }}
                            group={"treeGrid"}
                            treeDomId={"shareTreeDom"}
                        />
                    }, [dataSortable])
                }
            </div>
        )
    }
    const refreshSubject = (r: boolean) => {
        if (r) {
            getSubjectTypeData(diaParams.current);
            getSubjectListDatas(diaParams.current);
        }
    }

    const treeDragEnd = async (e: any, r: any) => {
        draggedTreeNode.current = e;
        // console.log(e, r, '@@@ e--------------');
    }
    function rightContainer() {
        return (
            <div style={{ width: '100%', height: '100%', display: "flex", marginLeft: '15px', }}>
                <div style={{ width: 'calc(100% - 65px)', height: "100%" }}>
                    {
                        // eslint-disable-next-line react-hooks/rules-of-hooks
                        useMemo(() => {
                            return <DevTreeRight gridData={dataSortable}
                                onItemClick={(e: any) => {
                                    console.log("itemDblClick @@@ ", tableRowData.current, e);
                                    onItemClick(e, tableRowData.current.rowIndex)
                                }} data={AccountFilterData}
                                treeDragEnd={treeDragEnd} DataId={diaParams.current?.DataId}
                                refreshSubject={refreshSubject} />
                        }, [AccountFilterData, dataSortable, tableRowData.current])
                    }
                </div>

                <div>
                    <div className="IconRefresh_Style" style={{ cursor: 'pointer', margin: '0 auto' }} >
                        <CpasIcon
                            type="icon-refresh"
                            fontSize={16}
                            onClick={() => {
                                refreshSubject(true);
                            }}
                        />
                    </div>
                    <HocVerticalLeftStyleTab
                        activeKey={tbsStates}
                        className='AccountSubjectsTabs'
                        tabPosition='left'
                        tabBarStyle={{ background: '#FFF' }}
                        onChange={(e: any) => { AccountTabsClick(e) }}
                    >
                        {Array.isArray(ficationTabsData) ?
                            ficationTabsData.map((item: any) => {
                                return <AntTabs.Panel
                                    tab={item.type}
                                    key={item.code}
                                    style={{ marginTop: "5px" }}
                                />
                            })
                            : <></>
                        }
                    </HocVerticalLeftStyleTab >
                </div>
            </div>

        )
    }
    const OK = async () => {
        setVisible(false);
        tableRowData.current = {};
        const r = await AdjustingEntryKMMapSave({
            dbname,
            billID: diaParams.current.BillID,
            Data_ID: diaParams.current.DataId,
            editUser: username
        })
        if (r) {
            diaParams.current.okClick();
        }
    }
    return (
        <div style={{ width: '100%', height: '100%' }}>
            <Popup
                shadingColor='rgba(0, 0, 0, 0)'
                shading={true}
                width='100%'
                height="100%"
                ref={ref}
                // dragOutsideBoundary={true}
                resizeEnabled={true}
                visible={visible}
                animation={{ duration: 3 }}
                title='设置重分类科目'
                minWidth={500}
                minHeight={300}
                {...props}
                {...size}
                onHiding={onHiding}
                onResizeEnd={(e) => {
                    setSize({ width: e.width, height: e.height });
                }}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: "before",
                        options: {
                            width: 150,
                            text: '设置自动重分科目',
                            onClick: () => {
                                SetReclassiFiedItemRef.current.show({
                                    ok: async () => {
                                        await KMMapanalysisMap({
                                            dbname,
                                            billID: diaParams.current.BillID,
                                            Data_ID: diaParams.current.DataId
                                        })
                                        getKMMapDataLists(diaParams.current);
                                        // await AdjustingEntryKMMapSave({
                                        //     dbname,
                                        //     billID: diaParams.current.BillID,
                                        //     Data_ID: diaParams.current.DataId,
                                        //     editUser: username
                                        // })
                                    }
                                })
                            }
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => {
                                onHiding()
                            }
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => OK()
                        },
                    },
                ]}
            >

                <div style={{ width: '100%', height: '100%', position: "relative" }} >
                    {openVisible111111 && <div style={{
                        position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center",
                        opacity: 0.5, zIndex: "99999", background: "#ddd"
                    }}>
                        <LoadIndicator id="medium-indicator" height={50} width={50} />
                    </div>}
                    <LayoutB
                        rowSize={["10%", "70%", "80%"]}
                        leftSlot={leftContainer()}
                        rightSlot={rightContainer()}
                    />
                </div >
            </Popup >
            <SetReclassiFiedItem ref={SetReclassiFiedItemRef} DataId={diaParams.current?.DataId} width={600} height={500} />
            <DevPopup.Default ref={DeletePopupRef} width={80} height={200} >
                {() => {
                    return <span>确定要执行此操作吗？</span>
                }}
            </DevPopup.Default>
        </div >
    )
});

export default React.memo(SetClassiFication); 